package com.lagou.edu.controller;

import com.lagou.edu.service.AuthCodeService;
import com.lagou.edu.service.EmailRpcService;
import com.lagou.edu.service.UserRpcService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/code/")
@Slf4j
public class CodeController {
    @Autowired
    private AuthCodeService authCodeService;

    // dubbo RPC
    @Reference
    private EmailRpcService emailRpcService;

    // dubbo RPC
    @Reference
    private UserRpcService userRpcService;

    // ⽣成验证码并发送到对应邮箱，成功true，失败false
    @GetMapping(value = "/create/{email}")
    public boolean create(@PathVariable("email") String email) {
        // 如果邮箱已经注册过，直接返回false
        if (userRpcService.isRegistered(email)) {
            return false;
        }

        String code = authCodeService.create(email);
        log.info("email={} code={}", email, code);
        return emailRpcService.send(email, code);
    }
}
